import mqtt from 'mqtt'

function newGuid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        const r = Math.random() * 16 | 0
        const v = c === 'x' ? r : (r & 0x3 | 0x8)
        return v.toString(16)
    })
}
const guid = newGuid()

export default {
    namespaced: true,
    state: {
        profile: {
            serverUrl: 'ws://192.168.65.13:8083/mqtt',
            // serverUrl: 'ws://10.109.88.193:443',
            options: {
                // 超时时间
                connectTimeout: 10000,
                // 认证信息
                clientId: guid,
                username: 'emqx-connect-via-websocket',
                password: 'emqx-connect-via-websocket'
            }
        },
        webSocket: null,
        webSocketData: null,
        webSocketAlarm: null,
        webSocketCommand: null,
        stationEvent: [],
        speaker: window.speechSynthesis
    },
    mutations: {
        setProfile(state, payload = {}) {
            state.profile = {...state.profile, ...payload }
        },
        setWebSocket(state, payload = null) {
            state.webSocket = payload
        },
        setWebSocketData(state, payload = null) {
            state.webSocketData = payload
        },
        setWebSocketAlarm(state, payload = null) {
            state.webSocketAlarm = payload
        },
        setWebSocketCommand(state, payload = null) {
            state.webSocketCommand = payload
        },
        setStationEvent(state, payload = []) {
            state.stationEvent = payload
        },
        addWebSocket(state, payload = null) {
            state.webSocketData = {...state.webSocketData, ...payload }
        }
    },
    actions: {
        async init({ dispatch, state }) {
            // dispatch('getStationEvent');
            // await dispatch('getProfile')
            await dispatch('initWebSocket')
        },
        async getStationEvent({ commit, rootState }) {
            const result = await rootState.service.getStationEvent(rootState.userProfile.station)
            if (result.flag) {
                commit('setStationEvent', result.data)
            }
        },
        addStationEvent({ commit, state }, payload) {
            commit('setStationEvent', state.stationEvent.push(payload))
        },
        removeStationEvent({ commit, state }, payload) {
            commit('setStationEvent', state.stationEvent.filter(item => item.uid !== payload.uid))
        },
        async getProfile({ commit, rootState }) {
            let result = await rootState.service.getWebSocket()
            if (result.flag && result.data && result.data.length > 0) {
                result = result.data.find(item => item.flag) || result.data[0]
                if (result) {
                    await commit('setProfile', result.info)
                }
            }
        },
        initWebSocket({ commit, dispatch, state }) {
            if (state.profile && state.profile.serverUrl && state.profile.serverUrl.trim) {
                if (state.webSocket) {
                    return
                }
                const webSocket = mqtt.connect(state.profile.serverUrl, state.profile.options)
                console.log('正在打开连接...:', state.profile.serverUrl)
                webSocket.on('error', (error) => {
                    console.log('连接失败(error):', error)
                })
                webSocket.on('offline', (error) => {
                    console.log('离线(offline):', error)
                })
                webSocket.on('close', (error) => {
                    console.log('关闭连接(close):', error)
                })
                webSocket.on('end', (error) => {
                    console.log('结束连接(end):', error)
                })
                webSocket.on('disconnect', (error) => {
                    console.log('丢失连接(disconnect):', error)
                })
                webSocket.on('reconnect', (error) => {
                    console.log('正在重连(reconnect):', error)
                })
                webSocket.on('connect', event => {
                    // console.log('连接成功(connect):', event)
                        // dispatch('onOpen', event)
                    webSocket.publish('web.mq', guid, (error) => {
                        console.log(error || '消息发布成功', guid)
                    })
                    webSocket.subscribe(guid, { qos: 1 })
                        // webSocket.subscribe(['csot_t4_p1_temp', 'csot_t4_p1_han'], { qos: 1 }, (error, granted) => {
                        //   if (!error) {
                        //     console.log('订阅成功', granted)
                        //   } else {
                        //     console.log('订阅失败', granted)
                        //   }
                        // })
                })
                webSocket.on('message', (topic, message) => {
                        console.log('收到来自', topic, '的消息', message.toString())
                        if (topic === guid) {
                            console.log('收到控制指令....')
                        } else {
                            console.log('收到信息=====')
                        }
                        dispatch('onRecived', { topic, message: JSON.parse(message) })
                    })
                    // await dispatch('close')
                commit('setWebSocket', webSocket)
            }
        },
        sendJson({ state }, event) {
            state.webSocket.send(JSON.stringify(event))
            console.log('发送数据:', event)
        },
        onOpen({ dispatch, rootState }, event) {
            for (const key in rootState.userProfile.station) {
                dispatch('subscribeAlarm', `*.${key}`)
            }
        },
        onRecived({ commit, state, rootState }, { topic, message }) {
            if (topic === guid) {
                commit('setWebSocketCommand', message)
            } else {
                // message = JSON.parse(message)
                // state.speaker.speak(new SpeechSynthesisUtterance(`收到消息:${message.msg}!`))
                commit('addWebSocket', message)
            }
            // try {
            //   let data = JSON.parse(message)
            //   if (data.v) {
            //     data = JSON.parse(data.v)
            //     console.log('ok', data)
            //     if (data &&
            //       data.tname &&
            //       data.tname.trim() &&
            //       data.tname.trim().toUpperCase() === state.profile.alarmCommand.trim().toUpperCase()) {
            //       const stationName = rootState.userProfile.station[data.station] ? rootState.userProfile.station[data.station].name : ''
            //       state.speaker.speak(new SpeechSynthesisUtterance(`告警:${stationName},${data.point},开关变位!`))
            //       state.stationEvent.push(data)
            //       commit('setStationEvent', state.stationEvent)
            //       const alarm = { ...data, 'stationName': stationName }
            //       commit('setWebSocketAlarm', alarm)
            //     }
            //   }
            // } catch (err) {
            //   console.log('err', message)
            // }
        },
        unSubscribe({ dispatch, state }, topic) {
            const event = {
                command: state.profile.unsubscribeCommand,
                content: topic
            }
            dispatch('sendJson', event)
        },
        subscribe({ dispatch, state }, topic) {
            // const event = {
            //   command: state.profile.subscribeCommand,
            //   content: topic
            // }
            // dispatch('sendJson', event)
            if (state.webSocket.connected) {
                state.webSocket.subscribe(topic, { qos: 1 }, (error) => {
                    if (!error) {
                        console.log('订阅成功', topic)
                    } else {
                        console.log('订阅失败', topic)
                    }
                })
            } else {
                dispatch('init')
            }
        },
        unSubscribeAlarm({ dispatch, state }, topic) {
            const event = {
                command: state.profile.unsubscribeCommand,
                content: `${topic}.${state.profile.alarmCommand}`
            }
            dispatch('sendJson', event)
        },
        subscribeAlarm({ dispatch, state }, topic) {
            const event = {
                command: state.profile.subscribeCommand,
                content: `${topic}.${state.profile.alarmCommand}`
            }
            dispatch('sendJson', event)
        },
        unSubscribeData({ dispatch, state }, topic) {
            const event = {
                command: state.profile.unsubscribeCommand,
                content: `${topic}.${state.profile.dataCommand}`
            }
            dispatch('sendJson', event)
        },
        subscribeData({ dispatch, state }, topic) {
            const event = {
                command: state.profile.subscribeCommand,
                content: `${topic}.${state.profile.dataCommand}`
            }
            dispatch('sendJson', event)
        },
        disconnect({ dispatch, state }, topic) {
            const event = {
                command: state.profile.disconnectCommand,
                content: topic
            }
            dispatch('sendJson', event)
        },
        close({ state }) {
            if (state.webSocket) {
                state.webSocket.close()
                console.log('关闭连接:', state.profile.serverUrl)
            }
        }
    }
}